<?php
if (!defined('IN_EBB') ) {
	die("<b>!!ACCESS DENIED HACKER!!</b>");
}
/**
Filename: function.php
Last Modified: 11/11/2011

Term of Use:
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/

/**
*trailingSlashRemover
*
*removes any extra / that some web server setup add to their DOCUMENT_ROOT settings.
*
*@modified 11/27/09
*
*@param string $str - variable to trim.
*
*
*@return string $str - trimmed path.
*/
function trailingSlashRemover($str) {
    #trim any unwanted things first.
    $str = trim($str);

    #ensure we don't remove all / in some cases.
    return $str == '/' ? $str : rtrim($str, '/');
}

/**
*removeEvilAttributes
*
*will remove any malicious attributes.
*
*@modified 10/5/09
*
*@param string $string - variable to clean.
*
*
*@return string $string - cleaned variable.
*/
function removeEvilAttributes($string){
	$stripAttrib = "' (style|class)=\"(.*?)\"'i";
	$string = stripslashes($string);
	$string = preg_replace($stripAttrib, '', $string);
	return $string;
}

/**
*var_cleanup
*
*will clean up a variable and free it up of damaging HTML code.
*
*@modified 10/5/09
*
*@param string $string - variable to clean.
*
*
*@return string $var - cleaned variable.
*/
function var_cleanup($string){
	return stripslashes(removeEvilAttributes(htmlentities($string, ENT_QUOTES, "UTF-8")));
}


/**
*formatTime
*
*Will format time based on user preference.
*
*@modified 9/8/09
*
*@param string $format - format in use.
*@param time() $time - timestamp generated by time()
*@param integer $GMT - GMT timezone to offset by.
*/
function formatTime($format, $time, $GMT){
	$gmtTime = gmdate ($format, $time);
	$formattedTime = date($format, strtotime("$GMT hours",strtotime($gmtTime)));
	
	return($formattedTime);
}

/**
 * Loads a URL using cURL.
 * @param string $url
 * @version 6/24/11
 * @return string
 */
function curlLoadFromUrl($url) {

	try {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);

		/* Check for 404 (file not found). */
		$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		if($httpCode == 404) {
			return null;
		}

		curl_close($curl);
		return $result;
	} catch(Exception $e) {
		$error = new notifySys($e, true, true, __FILE__, __LINE__);
		$error->genericError();
    }
  }

/**
*redirectToHttps
*
*Will direct user to a secure connection is SSL is setup.
*
*@modified 10/26/09
*/
function redirectToHttps(){
	if($_SERVER['HTTPS'] !== "on"){
		$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		header("Location: $redirect");
	}
}

/**
*redirect
*
*Will direct user to a defined location.
*
*@param string url - link to direct user to.
*@param bool delay - should the user wait to be redirected?
*@param int sec = seconds that user should wait before being redirected.
*
*@modified 11/11/11
*
*@note url parameter will only direct users to pages within the board, it
*won't redirect users to external links.
*/
function redirect($url, $delay, $sec){

	global $boardDir;

	#see if user will need wait for redirecting.
	if($delay == true){
	    #convert & to &amp; for HTML-valid reasons.
		$url = str_replace('&', '&amp;', $url);
		
		#direct user using the META tag.
		echo '<meta http-equiv="refresh" content="'.$sec.';url=/'.$boardDir."/".$url.'" />';
	}else{
	    #convert &amp; to &.
		$url = str_replace('&amp;', '&', $url);

		#direct user using HTTP/1.1 headers.
		header("Location: /".$boardDir."/".$url);
		exit();
	}
}

/**
*pagination
*
*Will format time based on user preference.
*
*@modified 10/5/09
*
*@param string $action - query string used wherer defined.
*
*
*@return string $pagination - completed pagination.
*/
function pagination($actions){

	global $num, $lang, $pg, $count, $count2, $perPg;

	// Figure out the total number of pages. Always round up using ceil()
	$total_pages = ceil($num / $perPg);
	$pagination = "<div class=\"pagination\"><p>$lang[pages]</p><ul>";
	// Build page number
	if($pg > 1){
		$prev = ($pg - 1);
		$pagination .= "<li class=\"disablepage\"><a href=\"$_SERVER[PHP_SELF]?".$actions."pg=$prev\">$lang[prev]</a></li>";
	}
	//output numbers.
	for($i = 1; $i <= $total_pages; $i++){
		#see if this is the current page.
		if($pg == $i){
			$pagination .= "<li class=\"currentpage\"><b>$i</b></li>";
		}else{
			#dot out a few page numbers to prevent rows of links. 
			if($pg > 4 && $i > 3 && $i < ($pg - 1) && $i < ($total_pages - 3)){
				$count ++;
				$pagination .= ($count == 1)? "<li>...</li>" : "";
			}elseif($i > ($pg + 2) && $i < ($total_pages - 2)){
				$count2 ++;
				$pagination .= ($count2 == 1)? "<li>...</li>" : "";
			}else{
				$pagination .= "<li><a href=\"$_SERVER[PHP_SELF]?".$actions."pg=$i\">$i</a></li>";
			}
		}
	}
	// Build Next Link
	if($pg < $total_pages){
		$next = ($pg + 1);
		$pagination .= "<li class=\"nextpage\"><a href=\"$_SERVER[PHP_SELF]?".$actions."pg=$next\">$lang[next]</a></li>";
	}
	$pagination .= "</ul></div>";

	return ($pagination);
}

/**
*boardStats
*
*Obtains a few stats about the board.
*
*@modified 11/12/10
*
*@return array $bStat - results of stats.
*/
function boardStats($type){

	global $db;
	
	#see what we'ree counting.
	switch($type){
	    case 'member':
			#get member count.
			$db->SQL = "SELECT id FROM ebb_users WHERE active='1'";
			return (number_format($db->affectedRows()));
	    break;
	    case 'topic':
			#get topic count.
			$db->SQL = "SELECT tid FROM ebb_topics";
			return (number_format($db->affectedRows()));
		break;
	    case 'post':
			#get post count.
			$db->SQL = "SELECT pid FROM ebb_posts";
			return (number_format($db->affectedRows()));
	    break;
	    case 'newuser':
			#get newest user.
			$db->SQL = "SELECT Username FROM ebb_users WHERE active='1' ORDER BY Date_Joined DESC LIMIT 1";
			return($db->fetchResults());
	    break;
	    default:
	        return (0);
	    break;
	}
}

/**
*checkInstall
*
*Checks to see if installation files are still on server.
*
*@modified 10/5/09
*
*
*@return integer $setupExist - results of check.
*/
function checkInstall(){

	if (file_exists("install/install.php")){
		$setupExist = 1;
	}else{
		$setupExist = 0;
	}
	return ($setupExist);
}

/**
*informationPanel
*
*loads data for infoBox.
*
*@modified 11/12/10
*
*@return string - infobox data.
*/
function informationPanel() {

	global $db, $title, $lang;
	
 	#SQL to get info data.
	$db->SQL = "SELECT information FROM ebb_information_ticker";
	$infoQ = $db->query();
	$infoCt = $db->affectedRows();
	
	#if no news exists on DB, just close it up.
	if($infoCt == 0){
	    #prime with stat-up data.
		$infoLst = '<ul id="news">'."\n".'
		<li><strong>'.$title.' - '.$lang['ticker_txt'].'</strong></li>'."\n".'
		<li>'.$lang['nonews'].'</li>'."\n".'</ul>';
	}else{
    	#prime with stat-up data.
		$infoLst = '<ul id="news">'."\n".'
		<li><strong>'.$title.' - '.$lang['ticker_txt'].'</strong></li>'."\n";
		
		#get info panel data.
		while ($infoR = mysql_fetch_assoc($infoQ)) {
			#populate list with information.
			$infoLst .= '<li>'.smiles(BBCode($infoR['information'])).'</li>'."\n";
		}

		#finish list.
		$infoLst . '</ul>';
	}

	return $infoLst;
}

/**
*newpost_counter
*
*get a collection of unread topics for search engine results.
*
*@modified 10/5/09
*
*
*@return integer $count - results of count.
*/
function newpost_counter(){

	global $search_result, $search_result2, $logged_user, $db;
	//output any topics
	$count = 0;	 
	#get topic count.
	while ($r = mysql_fetch_assoc($search_result)) {
		$db->SQL = "select Topic from ebb_read_topic WHERE Topic='$r[tid]' and User='$logged_user'";
		$read_stat = $db->affectedRows();

		if ($read_stat == 0){
			//increment count
			$count++;
		}
	}
	#post count
	while ($r2 = mysql_fetch_assoc($search_result2)){
		//see if post is new.
		$db->SQL = "select Topic from ebb_read_topic WHERE Topic='$r2[tid]' and User='$logged_user'";
		$read_stat2 = $db->affectedRows();

		if ($read_stat2 == 0){
			//increment count
			$count++;
		}
	}
	return ($count);
}

/**
*ip_checker
*
*Get information regarding IP Address of user.
*
*@modified 10/5/09
*
*
*@return string $iplist - IP Information.
*/
function ip_checker(){

	global $u, $ip, $lang, $db;

	$db->SQL = "select Username from ebb_users where Username='$u' or IP='$ip'";
	$query = $db->query();

	$iplist = '';
	while ($row = mysql_fetch_assoc ($query)){
		//get number of times the ip was used by this user.
		$db->SQL = "select author from ebb_topics where author='$row[Username]' and IP='$ip'";
		$count1 = $db->affectedRows();

		
		$db->SQL = "select re_author from ebb_posts where re_author='$row[Username]' and IP='$ip'";
		$count2 = $db->affectedRows();

		$total_count = $count1 + $count2;

		$iplist .= "$row[Username] - $total_count $lang[posts]<br />";
	}
	return $iplist;
}

/**
*other_ip_checker
*
*Get information regarding IP Address of user that they are tied to.
*
*@modified 10/5/09
*
*
*@return string $iplist - IP Information.
*/
function other_ip_check(){

	global $ip, $u, $db;

	#topic IP check.
   	$db->SQL = "select DISTINCT IP from ebb_topics where author='$u'";
	$q = $db->query();
	$ip_ct = $db->affectedRows();

	$ipcheck = '';
	if($ip_ct > 0){
		while ($row = mysql_fetch_assoc ($q)){
			//get number of times the ip was used by this user.
			$ipcheck .= "$row[IP]<br />";
		}
	}
	#post IP check.
   	$db->SQL = "select DISTINCT IP from ebb_posts where re_author='$u'";
	$q2 = $db->query();
	$ip2_ct = $db->affectedRows();


	if($ip2_ct > 0){
		while ($row2 = mysql_fetch_assoc ($q2)){
			//get number of times the ip was used by this user.
			$ipcheck .= "$row[IP]<br />";
		}
	}
	return ($ipcheck);
}
?>
